// JWT工具函数
import { sign, verify } from '@tsndr/cloudflare-worker-jwt';

export async function generateToken(payload, secret, expiresIn = '1h') {
  const now = Math.floor(Date.now() / 1000);
  const exp = now + (expiresIn === '7d' ? 7 * 24 * 60 * 60 : 60 * 60); // 1小时或7天

  const token = await sign({
    ...payload,
    iat: now,
    exp
  }, secret);

  return token;
}

export async function verifyToken(token, secret) {
  const isValid = await verify(token, secret);
  if (!isValid) {
    throw new Error('Invalid token');
  }
  
  return decode(token);
}

function decode(token) {
  const base64Url = token.split('.')[1];
  const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
  const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  }).join(''));

  return JSON.parse(jsonPayload);
}
